{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "75e2c1fe-8a06-4f0b-8fd6-d1b6d10ce82f",
   "metadata": {},
   "source": [
    "# Quantum Phase Estimation (QPE) for Solving Molecular Energies\n",
    "\n",
    "\n",
    "Quantum Phase Estimation (QPE) is a key algorithm in quantum computing, allowing one to estimate the phase (or eigenvalue) of an eigenvector of a unitary operation. The algorithm is designed so, that for a given Hamiltonian $H$, and an eigenvalue ${|\\psi\\rangle}$, the output that will be obtained is $\\epsilon$ where\n",
    "\n",
    "$U{|\\psi\\rangle} = e^{2\\pi i\\epsilon}{|\\psi\\rangle} , U = e^{2\\pi iH}$ .\n",
    "\n",
    "\n",
    "Therefore, by measuring the phase accumulated, the QPE algorithm allows calculating the energies relating to the chosen initial state.\n",
    "When using QPE for chemistry problems, it is common to search for the lowest energy of a given molecule. As the molecule can be written in the form of a Hamiltonian (Hermitian matrix which meaning is the energetic forces of the structure), usually symbolized by \"H\", one only need to insert the ground eigenvector in order to obtain the minimal energy value using QPE. However, obtaining the ground state is not a trivial problem. In order to overcome it, it is sufficient to use a state with big overlap with the ground state.\n",
    "\n",
    "We define a state ${|v\\rangle}$ which will be chosen as the algorithm's initial state. Let us define {$\\psi_i$} to be the set of (unknown) eigenvalues of $H$. Generally, any vector can be rewritten as a superposition of any basis set, thus -\n",
    "\n",
    "${|v\\rangle} = \\sum_i a_i{|\\psi_i\\rangle}$\n",
    "\n",
    "and -\n",
    "\n",
    "$U{|v\\rangle} = \\sum_i a_i e^{2\\pi i\\epsilon_i}{|\\psi_i\\rangle}$.\n",
    "\n",
    "where ${\\epsilon_i}$ are the eigenvalues of H, i.e. the span of energies relating to the molecule. Using execution with enough shots, one will obtain this set of $\\theta_i$, i.e., a subset of the Hamiltonian's eigenvalues. As we are specifically interested in $\\epsilon_0$, the ground state of H, it is important that there is a large overlap between ${\\psi_0}$ and ${|v\\rangle}$ so the probability to measure ${\\epsilon_0}$ is high, i.e.\n",
    "\n",
    "$P(\\epsilon_0) = |\\langle v|\\psi_0\\rangle|^2 > \\epsilon $.\n",
    "\n",
    "How large is $\\epsilon$? After execution, we will obtain a set of ${E_i}$.\n",
    "If we have done 1000 shots of execution, and $P(\\epsilon_0)>1$, it should be measured is about 10 times to get a good statistical variance.\n",
    "\n",
    "A common choice for ${|v\\rangle}$ (the initial state) is the Hartree-Fock (HF) state, which with good probability have a large overlap with the ground state. However, other guesses for the initial state are possibly good or even better fit, and choosing the right initial state is a sort of art and an active field of research.\n",
    "\n",
    "For further reading about QPE we recommend [[1](#NC)].\n",
    "\n",
    "\n",
    "#### What are the benefits of using QPE algorithm for finding a molecule's ground state?\n",
    "\n",
    "The two most prominent methods to solve ground energy for molecules are quantum variational algorithm (VQE) and QPE. Those promise better scalability compared to classical counterparts as the molecules becomes more complex, with larger number of electrons manifesting as more degrees of freedom for the problem.\n",
    "\n",
    "While so, the number of parameters in VQE is closely related to the number of electrons. This may create inherent difficulty achieving high-precision calculations through sampling statistical estimators, and paraphs even not converge for very large systems. While so, the number of parameters in QPE is a flexible value which is directly related to the resolution of the problem, but is not bonded with the number of electrons.\n",
    "\n",
    "Furthermore, it is known that advanced quantum algorithms based on QPE can perform electronic structure calculations in sub-exponential time with accuracy that rivals exact diagonalization methods. This guarantee of simultaneously achieving high accuracy, efficiency, and generality is a feat that is believed to be impossible for classical algorithms. For those reasons, VQE is applicable in the near term (NISQ) era, while QPE is suited for fault-tolerant design.\n",
    "\n",
    "#### During this tutorial, we will follow the QPE algorithms steps as following:\n",
    "\n",
    "a. Define a molecule and convert it into a Hamiltonian H, manifested as a pauli list.\n",
    "\n",
    "b. Prepare the Hamiltonian for QPE: including normalization and choosing the resolution.\n",
    "\n",
    "c. Initializing the state for the HF state.\n",
    "\n",
    "d. Preparing the quantum circuit.\n",
    "\n",
    "e. Executing the circuit to find the related phases and analyzing the results to find the ground state.\n",
    "\n",
    "f. Comparing the QPE results with exact solution for the molecule\u2019s ground state."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cd71faa-1ef3-4d67-8c9a-d66e0a895b9a",
   "metadata": {},
   "source": [
    "## 0. Pre-requirments\n",
    "\n",
    "The model is using several Classiq's libraries in addition to IBM's simulating tool."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "11eaf8f8-c06e-443e-ac74-5aa364f5198c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:36.283533Z",
     "iopub.status.busy": "2024-05-07T15:16:36.283079Z",
     "iopub.status.idle": "2024-05-07T15:16:39.275433Z",
     "shell.execute_reply": "2024-05-07T15:16:39.274629Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import scipy\n",
    "from numpy import linalg as LA\n",
    "\n",
    "# for state preperation and phase estimation\n",
    "from classiq import Constraints, Preferences\n",
    "\n",
    "# for chemistry\n",
    "from classiq.applications.chemistry import Molecule, MoleculeProblem, PauliOperator"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ac537458-568d-4718-9020-408cc7232641",
   "metadata": {},
   "source": [
    "## 1. Create Your Molecule"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2b67b2e1-94c2-4c8f-8ee9-577c79a7234f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:39.279850Z",
     "iopub.status.busy": "2024-05-07T15:16:39.279309Z",
     "iopub.status.idle": "2024-05-07T15:16:39.288752Z",
     "shell.execute_reply": "2024-05-07T15:16:39.288033Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# build your molecule\n",
    "\n",
    "molecule_H2 = Molecule(atoms=[(\"H\", (0.0, 0.0, 0)), (\"H\", (0.0, 0.0, 0.735))])\n",
    "molecule_O2 = Molecule(atoms=[(\"O\", (0.0, 0.0, 0)), (\"O\", (0.0, 0.0, 1.16))])\n",
    "molecule_LiH = Molecule(atoms=[(\"H\", (0.0, 0.0, 0.0)), (\"Li\", (0.0, 0.0, 1.596))])\n",
    "molecule_H2O = Molecule(\n",
    "    atoms=[(\"O\", (0.0, 0.0, 0.0)), (\"H\", (0, 0.586, 0.757)), (\"H\", (0, 0.586, -0.757))]\n",
    ")\n",
    "molecule_BeH2 = Molecule(\n",
    "    atoms=[(\"Be\", (0.0, 0.0, 0.0)), (\"H\", (0, 0, 1.334)), (\"H\", (0, 0, -1.334))]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9e37fada-9ecc-4a24-bf2c-0994e9c14149",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:39.293443Z",
     "iopub.status.busy": "2024-05-07T15:16:39.292243Z",
     "iopub.status.idle": "2024-05-07T15:16:39.297244Z",
     "shell.execute_reply": "2024-05-07T15:16:39.296486Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# define your molecule\n",
    "\n",
    "molecule = molecule_H2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "5d27e5df-e16e-44b2-b78a-187905577908",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:39.301806Z",
     "iopub.status.busy": "2024-05-07T15:16:39.300600Z",
     "iopub.status.idle": "2024-05-07T15:16:41.781375Z",
     "shell.execute_reply": "2024-05-07T15:16:41.780596Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your Hamiltonian is\n",
      "-1.041 * I\n",
      "-0.796 * Z\n",
      "+0.181 * X\n"
     ]
    }
   ],
   "source": [
    "# define your molecule problem\n",
    "\n",
    "gs_problem = MoleculeProblem(\n",
    "    molecule=molecule,\n",
    "    basis=\"sto3g\",\n",
    "    mapping=\"jordan_wigner\",  #'bravyi_kitaev'\n",
    "    z2_symmetries=True,\n",
    "    freeze_core=True,\n",
    ")\n",
    "\n",
    "operator = gs_problem.generate_hamiltonian()\n",
    "gs_problem = gs_problem.update_problem(operator.num_qubits)\n",
    "print(\"Your Hamiltonian is\", operator.show(), sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7a0b57c6-a057-41cb-8163-cc91d559bbdd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.786010Z",
     "iopub.status.busy": "2024-05-07T15:16:41.784773Z",
     "iopub.status.idle": "2024-05-07T15:16:41.791592Z",
     "shell.execute_reply": "2024-05-07T15:16:41.790923Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your Pauli list is\n",
      "[('I', (-1.041093141516624+0j)), ('Z', (-0.7958748496863586+0j)), ('X', (0.18093119978423122+0j))]\n"
     ]
    }
   ],
   "source": [
    "pauli_ops = operator.pauli_list\n",
    "N = operator.num_qubits\n",
    "print(\"Your Pauli list is\", pauli_ops, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "685f4a01-caf3-4d0c-b9f3-4fc89bc5192a",
   "metadata": {},
   "source": [
    "## 2. Preparing the Molecule for QPE"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b1bafad-d35c-4504-9665-02b0ae86d52f",
   "metadata": {},
   "source": [
    "### 2.1 Chose the Algorithm's Precision\n",
    "\n",
    "For QPE algorithms, the precision is set by the number of qubits chosen $n$, such that the resolution is $1/{2^n}$. In case the matrix needs to be normlized, the resolution will be distorted. In case of normalization, that the span of results in the QPE is strached between the lowest and highest possible phase, thus the reslution will be mapped to $normalization-coefficient/{2^n} ~\\sim 1/{((\\lambda_{max}-\\lambda_{min})*2^n)}$.\n",
    "\n",
    "Here you can chose the precision in the parameter `n_qpe`, or by setting your desired resolution. If you chose your desired resolution and set the parameter `get_recommended_n` to be True, the number of qubits will be calculated for you accordingly.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4e96164f-aa00-4723-9f59-b1c13ccb58d8",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.796364Z",
     "iopub.status.busy": "2024-05-07T15:16:41.795124Z",
     "iopub.status.idle": "2024-05-07T15:16:41.800121Z",
     "shell.execute_reply": "2024-05-07T15:16:41.799301Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# `n_qpe`-  The precision of the QPE (the number of qubits to be used in the QPE. Creates resolution of 1/2^n_qpe\n",
    "n_qpe = 6"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "74aeea8b-1e16-408f-bc5f-c5888b552a6f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.804701Z",
     "iopub.status.busy": "2024-05-07T15:16:41.803523Z",
     "iopub.status.idle": "2024-05-07T15:16:41.810737Z",
     "shell.execute_reply": "2024-05-07T15:16:41.810086Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# recommanded n_qpe:\n",
    "get_recommanded_n = False\n",
    "\n",
    "import math\n",
    "\n",
    "desired_resolution = 0.02\n",
    "\n",
    "\n",
    "def get_nqpe(pauli_operator, desired_resolution):\n",
    "    N = pauli_operator.num_qubits\n",
    "    A = 0\n",
    "    for a, b in pauli_operator.pauli_list:\n",
    "        A = A + abs(b)\n",
    "    nqpe = math.log2(2 * N * A / desired_resolution)\n",
    "    return math.ceil(nqpe)\n",
    "\n",
    "\n",
    "if get_recommanded_n:\n",
    "    n_qpe = get_nqpe(operator, desired_resolution)\n",
    "    print(\"number of qubits for QPE is\", n_qpe)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fa3d1079-c12b-48db-8935-1ea059fdbce9",
   "metadata": {},
   "source": [
    "### 2.3 Normalize the Matrix\n",
    "\n",
    "As QPE obtains a phase in the form $e^{2\\pi i\\theta}$, there is meaning only for $\\theta \\in [0,2\\pi)$. Generally, our matrix M can have any eigenvalue, thus \\theta can have any value. In order to fix this discrepancy, the values of the matrix are stretched to be rescaled. We assume\n",
    "$\\theta \\in [\\lambda_{min}, \\lambda_{max}]$\n",
    "and use a normalization function in order to map those values into $[0, 1-1/{2^n}]$, where n is the number of qubits chosen for the QPE process in section 2.2.\n",
    "\n",
    "We perform the normalization procedure as following:\n",
    "\n",
    "a. We evaluate $\\lambda_{min},\\lambda_{max}$ (in the function ` normalization_params()` below). In order to do so we use rough estimation of the absolute max value that can take place by adding together all the pauli coefficients and multiplying by the matrix's dimensions. That will yield us a value $\\lambda$ (which is referred in the code as `normalization_coeff`) and we now assume that the domain is $\\theta \\in [-\\lambda, \\lambda]$.\n",
    "In general, one can build a more accurate assessment, which will decrease the span of solutions and thus achieve a better resolution.\n",
    "\n",
    "b. We make sure only positive values are available by adding $\\lambda*I^n$ to the pauli list. Now our evaluated span is $[0, 2*\\lambda]$.\n",
    "\n",
    "c. We normlize our matrix by multiplying all of the pauli coefficients by $(1-1/2^n)/(2*\\lambda)$. Now the span of $\\theta$ is $[0, 1-1/2^n]$, as required for proper QPE process.\n",
    "\n",
    "The values of the matrix's eigenvalues should be now between $0$ to $1-(1/2^n)$. The QPE procedure will be performed on this new normalized matrix. After the phases are obtained, the original phases of the pre-normalized matrix will be gathered by performing opposite steps to this normalization procedure.\n",
    "\n",
    "* Note that in case your matrix's eigenvalues are naturally between the values $0$ to $1-(1/2^n)$, you may not want to normalize it, as the normalization procedure may enlarge the span, thus lowering the resolution of the agorithm. In that case, you may skip those lines or change the value `normalize` to False."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "70d8b16f-5f50-4272-9b7b-0ca7cad00b60",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.815396Z",
     "iopub.status.busy": "2024-05-07T15:16:41.814254Z",
     "iopub.status.idle": "2024-05-07T15:16:41.824473Z",
     "shell.execute_reply": "2024-05-07T15:16:41.823778Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('I', (0.23825359047723227+0j)), ('Z', (-0.1941225083639407+0j)), ('X', (0.04413108211329154+0j))]\n"
     ]
    }
   ],
   "source": [
    "from typing import cast\n",
    "\n",
    "from classiq import Pauli, PauliTerm\n",
    "\n",
    "# normalizing the operator\n",
    "## we need to create a matrix such that its normalized version will have eigenvalues of [0,1/2^k] when k is the resolution of the QPE\n",
    "normalize = True\n",
    "\n",
    "\n",
    "def normalization_params(pauli_list, N):\n",
    "    A = 0\n",
    "    for a, b in pauli_list:\n",
    "        A = A + abs(b)\n",
    "    return N * A\n",
    "\n",
    "\n",
    "def normalize_hamiltonian(pauli_list, normalization_coeff, k):\n",
    "    new_pauli_list = []\n",
    "    for a, b in pauli_list:\n",
    "        if a == \"I\" * N:\n",
    "            new_pauli_list.append(\n",
    "                (\n",
    "                    a,\n",
    "                    (b + normalization_coeff)\n",
    "                    * (1 - 1 / (2**k))\n",
    "                    / (2 * normalization_coeff),\n",
    "                )\n",
    "            )\n",
    "        else:\n",
    "            new_pauli_list.append((a, b * (1 - 1 / (2**k)) / (2 * normalization_coeff)))\n",
    "    return new_pauli_list\n",
    "\n",
    "\n",
    "pauli_list = pauli_ops\n",
    "if normalize:\n",
    "    normalization_coeff = normalization_params(pauli_ops, N)\n",
    "    new_pauli_list = normalize_hamiltonian(pauli_ops, normalization_coeff, n_qpe)\n",
    "    pauli_ops = new_pauli_list\n",
    "    print(pauli_ops)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21e4de42-3417-46d4-b981-664bb0683dc4",
   "metadata": {},
   "source": [
    "Convert the objects to qmod:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "e340b469-5566-4bd5-bb5d-3107ebc790e0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.828923Z",
     "iopub.status.busy": "2024-05-07T15:16:41.827843Z",
     "iopub.status.idle": "2024-05-07T15:16:41.834314Z",
     "shell.execute_reply": "2024-05-07T15:16:41.833663Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "CHAR_TO_STUCT_DICT = {\"I\": Pauli.I, \"X\": Pauli.X, \"Y\": Pauli.Y, \"Z\": Pauli.Z}\n",
    "\n",
    "\n",
    "def pauli_str_to_enums(pauli):\n",
    "    return [CHAR_TO_STUCT_DICT[s] for s in pauli]\n",
    "\n",
    "\n",
    "def pauli_list_to_hamiltonian(pauli_list):\n",
    "    return [\n",
    "        PauliTerm(\n",
    "            pauli=pauli_str_to_enums(pauli), coefficient=cast(complex, coeff).real\n",
    "        )\n",
    "        for pauli, coeff in pauli_list\n",
    "    ]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62d2e51d-d532-4c26-86dd-a5b9b40d009e",
   "metadata": {},
   "source": [
    "## 3. Creating the Quantum Circuit\n",
    "\n",
    "We will now create a quantum circuit of the QPE algorithm using the Classiq platform. The user is able to fill in their constraints and preferences as desired."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "fd4ee616-2a11-46ba-adc0-ed5171d7dd7d",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.838788Z",
     "iopub.status.busy": "2024-05-07T15:16:41.837667Z",
     "iopub.status.idle": "2024-05-07T15:16:41.842620Z",
     "shell.execute_reply": "2024-05-07T15:16:41.841962Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "constraints = Constraints()\n",
    "preferences = Preferences(timeout_seconds=600)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "43c249a1-9db3-4164-bec1-f345670d4cd1",
   "metadata": {},
   "source": [
    "### 3.1. Create the phase estimation model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "b05c5ced-e02a-4b56-acc5-c62de3564239",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.847063Z",
     "iopub.status.busy": "2024-05-07T15:16:41.845892Z",
     "iopub.status.idle": "2024-05-07T15:16:41.856296Z",
     "shell.execute_reply": "2024-05-07T15:16:41.855646Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from classiq import molecule_problem_to_qmod\n",
    "from classiq.qmod import (\n",
    "    CInt,\n",
    "    Output,\n",
    "    QArray,\n",
    "    QBit,\n",
    "    QCallable,\n",
    "    QNum,\n",
    "    allocate,\n",
    "    allocate_num,\n",
    "    control,\n",
    "    invert,\n",
    "    qfunc,\n",
    "    repeat,\n",
    ")\n",
    "from classiq.qmod.builtins import (\n",
    "    H,\n",
    "    apply_to_all,\n",
    "    exponentiation_with_depth_constraint,\n",
    "    molecule_hartree_fock,\n",
    "    qft,\n",
    ")\n",
    "from classiq.qmod.symbolic import log, pi\n",
    "\n",
    "# this constant will be multipled be a linear factor for each qbit of the qpe, so the\n",
    "# depth will scale linear with the power of each unitary, on the expense of approximating the\n",
    "# exponentiation function\n",
    "exp_max_depth = 2200\n",
    "\n",
    "\n",
    "# define a Quantum Phase Estimation function that allows specifying each controlled\n",
    "# power unitary directly\n",
    "@qfunc\n",
    "def my_flexible_qpe(\n",
    "    unitary_with_power: QCallable[CInt],\n",
    "    phase: QArray[QBit],\n",
    ") -> None:\n",
    "    apply_to_all(H, phase)\n",
    "\n",
    "    repeat(\n",
    "        count=phase.len,\n",
    "        iteration=lambda index: control(\n",
    "            ctrl=phase[index],\n",
    "            operand=lambda: unitary_with_power(2**index),\n",
    "        ),\n",
    "    )\n",
    "    invert(lambda: qft(phase))\n",
    "\n",
    "\n",
    "@qfunc\n",
    "def main(reg: Output[QArray[QBit]], phase: Output[QNum]):\n",
    "    allocate_num(num_qubits=n_qpe, is_signed=False, fraction_digits=n_qpe, out=phase)\n",
    "    allocate(N, reg)\n",
    "\n",
    "    # The state chosen for the initial state is HF, as usually it has good overlap with the with the eigenstate of minimal energy.\n",
    "    molecule_hartree_fock(molecule_problem_to_qmod(gs_problem), reg)\n",
    "\n",
    "    # # Hereby we send the pauli list created for the molecule for creating phase estimation circuit.\n",
    "    my_flexible_qpe(\n",
    "        lambda power: exponentiation_with_depth_constraint(\n",
    "            pauli_list_to_hamiltonian(pauli_ops),\n",
    "            evolution_coefficient=-2 * np.pi * power,\n",
    "            max_depth=exp_max_depth * ((2**0.5) ** log(power, 2)),\n",
    "            qbv=reg,\n",
    "        ),\n",
    "        phase,\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "467eca03-8a66-43d8-b2af-6d86b21e36d5",
   "metadata": {
    "tags": []
   },
   "source": [
    "## 3.2. Synthesizing the Circuit\n",
    "\n",
    "Hereby we syntesize the circuit and show it using the analyzer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "10eaa569-de42-41b4-b615-c04bdc850ecf",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.861003Z",
     "iopub.status.busy": "2024-05-07T15:16:41.859910Z",
     "iopub.status.idle": "2024-05-07T15:16:41.880458Z",
     "shell.execute_reply": "2024-05-07T15:16:41.879759Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from classiq import create_model\n",
    "from classiq.execution import ExecutionPreferences\n",
    "\n",
    "num_shots = 200000\n",
    "\n",
    "qmod = create_model(\n",
    "    main,\n",
    "    constraints=constraints,\n",
    "    preferences=preferences,\n",
    "    execution_preferences=ExecutionPreferences(num_shots=num_shots),\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a7aae67f-1750-43be-9446-74fa0565058a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.885344Z",
     "iopub.status.busy": "2024-05-07T15:16:41.884136Z",
     "iopub.status.idle": "2024-05-07T15:16:41.904022Z",
     "shell.execute_reply": "2024-05-07T15:16:41.903307Z"
    }
   },
   "outputs": [],
   "source": [
    "from classiq import write_qmod\n",
    "\n",
    "write_qmod(qmod, name=\"qpe_for_molecules\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "8d434afe-5cbc-4a56-a48c-e657090c348a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:16:41.909027Z",
     "iopub.status.busy": "2024-05-07T15:16:41.907875Z",
     "iopub.status.idle": "2024-05-07T15:20:36.342504Z",
     "shell.execute_reply": "2024-05-07T15:20:36.341786Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening: https://platform.classiq.io/circuit/318dc444-650c-406f-976f-3d87f16775b1?version=0.41.0.dev39%2B79c8fd0855\n"
     ]
    }
   ],
   "source": [
    "from classiq import show, synthesize\n",
    "\n",
    "qprog = synthesize(qmod)\n",
    "show(qprog)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7483f266-af0f-4d08-aa96-317b4044df58",
   "metadata": {},
   "source": [
    "# 4. Measurment and Analysis\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e5bf0b3c-839f-43de-9da1-cba55ceba995",
   "metadata": {},
   "source": [
    "### 4.1. Circuit Execution\n",
    "\n",
    "The circuit is now sent to execution on a default simulator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "bc063bfc-de4b-4181-82b1-f805f86baa2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:20:36.347128Z",
     "iopub.status.busy": "2024-05-07T15:20:36.345984Z",
     "iopub.status.idle": "2024-05-07T15:21:50.459583Z",
     "shell.execute_reply": "2024-05-07T15:21:50.458947Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from classiq import execute\n",
    "\n",
    "results = execute(qprog).result()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "05e682bd-0f1a-4e10-ba0b-e0bf3378fecd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.462348Z",
     "iopub.status.busy": "2024-05-07T15:21:50.461903Z",
     "iopub.status.idle": "2024-05-07T15:21:50.464971Z",
     "shell.execute_reply": "2024-05-07T15:21:50.464409Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from classiq.execution import ExecutionDetails\n",
    "\n",
    "results = results[0].value"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8611351f-1b14-4969-878d-6f022cdfce2a",
   "metadata": {},
   "source": [
    "### 4.2. Presenting the Result's Count"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9c0ee98c-3ffa-4f1d-9cb2-4fada19b08b4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.467938Z",
     "iopub.status.busy": "2024-05-07T15:21:50.466973Z",
     "iopub.status.idle": "2024-05-07T15:21:50.474468Z",
     "shell.execute_reply": "2024-05-07T15:21:50.473904Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'phase': 0.046875}: 82380,\n",
       " {'phase': 0.03125}: 77825,\n",
       " {'phase': 0.0625}: 9006,\n",
       " {'phase': 0.015625}: 8723,\n",
       " {'phase': 0.078125}: 3270,\n",
       " {'phase': 0.0}: 3083,\n",
       " {'phase': 0.4375}: 2493,\n",
       " {'phase': 0.09375}: 1689,\n",
       " {'phase': 0.984375}: 1655,\n",
       " {'phase': 0.109375}: 1082]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "results.parsed_counts_of_outputs(\"phase\")[:10]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41009d2c-4276-409b-b9f4-8dee8103f208",
   "metadata": {},
   "source": [
    "### 4.3. Chosing the Most Probable Solution\n",
    "\n",
    "Hereby the user will choose the number of eigenvalues they wish to extract from the poll of results. The \n",
    "value `number_of_solutions` will determine how many results out of `qpe_results` will be analyzed. \n",
    "The `parsed_counts` property is already sorted.\n",
    "\n",
    "We get the result in the `phase` variable already encoded as fixed point variable in the range [0,1]."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "ba022acc-738c-4685-a7ff-70ea2c400bfd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.476943Z",
     "iopub.status.busy": "2024-05-07T15:21:50.476435Z",
     "iopub.status.idle": "2024-05-07T15:21:50.479735Z",
     "shell.execute_reply": "2024-05-07T15:21:50.479163Z"
    }
   },
   "outputs": [],
   "source": [
    "number_of_solutions = 1  # to be set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "4a54cb17-8c0a-4b00-a3a3-6e276fa92b53",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.482120Z",
     "iopub.status.busy": "2024-05-07T15:21:50.481642Z",
     "iopub.status.idle": "2024-05-07T15:21:50.488542Z",
     "shell.execute_reply": "2024-05-07T15:21:50.487983Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your qubit solution is\n",
      "[{'phase': 0.046875}: 82380]\n"
     ]
    }
   ],
   "source": [
    "solutions = results.parsed_counts_of_outputs(\"phase\")[:number_of_solutions]\n",
    "print(\"Your qubit solution is\", solutions, sep=\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f784e6f-d7ed-4cc9-81dd-f6b952d0dc01",
   "metadata": {},
   "source": [
    "### 4.4. Translating into Energy value (Phase)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d83d16de-2450-4c7a-8093-26bf13d4dce4",
   "metadata": {},
   "source": [
    "Map the phase back into the original values, i.e. renormalized into it's original span."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "836084e1-a20d-4a55-93cc-91a40c1d2f53",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.491382Z",
     "iopub.status.busy": "2024-05-07T15:21:50.491220Z",
     "iopub.status.idle": "2024-05-07T15:21:50.494025Z",
     "shell.execute_reply": "2024-05-07T15:21:50.493447Z"
    }
   },
   "outputs": [],
   "source": [
    "def post_process_phase(phase):\n",
    "    return (\n",
    "        (phase * 2 * normalization_coeff) / (1 - (1 / 2**n_qpe))\n",
    "    ) - normalization_coeff"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "a5bdb723-b015-4e80-98ea-985901c6c8d7",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.496211Z",
     "iopub.status.busy": "2024-05-07T15:21:50.495859Z",
     "iopub.status.idle": "2024-05-07T15:21:50.499028Z",
     "shell.execute_reply": "2024-05-07T15:21:50.498455Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# renormalize into the \"real\" solution -\n",
    "if normalize:\n",
    "    solution = [post_process_phase(value.state[\"phase\"]) for value in solutions]\n",
    "else:\n",
    "    solution = phase"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c963b82-26a7-4251-bae0-32e66c57fa1d",
   "metadata": {},
   "source": [
    "The final results of the Energy (matrix's eigenvlues) is therefore:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "43e8ec8f-2be9-403d-8ae9-9380fb2b08c9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.501429Z",
     "iopub.status.busy": "2024-05-07T15:21:50.500917Z",
     "iopub.status.idle": "2024-05-07T15:21:50.504469Z",
     "shell.execute_reply": "2024-05-07T15:21:50.503902Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-1.8257183156550982]\n"
     ]
    }
   ],
   "source": [
    "print(solution)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7565aa1f-b8ba-4617-a2ef-79317261dfe7",
   "metadata": {},
   "source": [
    "And the results including the error contributed from the resolution (number of qubits participating in the QPE) are:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "79f1c1ba-61fd-438e-a3d5-7606ea95e70f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.506581Z",
     "iopub.status.busy": "2024-05-07T15:21:50.506402Z",
     "iopub.status.idle": "2024-05-07T15:21:50.510455Z",
     "shell.execute_reply": "2024-05-07T15:21:50.509818Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "the resolution of result is 0.06406029177737187\n",
      "the eneregy solution is beteen -1.88977860743247 and -1.7616580238777264\n"
     ]
    }
   ],
   "source": [
    "if normalize:\n",
    "    energy_resolution = (\n",
    "        (1 / (2**n_qpe)) * 2 * normalization_coeff / (1 - (1 / 2**n_qpe))\n",
    "    )\n",
    "else:\n",
    "    energy_resolution = 1 / (2**n_qpe)\n",
    "\n",
    "print(\"the resolution of result is\", energy_resolution)\n",
    "\n",
    "for sol in solution:\n",
    "    print(\n",
    "        \"the eneregy solution is beteen\",\n",
    "        sol - energy_resolution,\n",
    "        \"and\",\n",
    "        sol + energy_resolution,\n",
    "    )\n",
    "\n",
    "    ###if zero or exceed the normalization range need to add conditions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d570c6b0-bd32-40d1-9ebb-c1ee7c8663ad",
   "metadata": {},
   "source": [
    "### 4.4. Find Exact Solution for Comparison"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "bd9e84a5-d131-4835-bade-13ba01035b44",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.512649Z",
     "iopub.status.busy": "2024-05-07T15:21:50.512475Z",
     "iopub.status.idle": "2024-05-07T15:21:50.516587Z",
     "shell.execute_reply": "2024-05-07T15:21:50.515949Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "exact result: -1.8572750302023786\n"
     ]
    }
   ],
   "source": [
    "mat = operator.to_matrix()\n",
    "w, v = np.linalg.eig(mat)\n",
    "print(\"exact result:\", np.real(min(w)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "703c6ae7-5174-433f-ad9f-78f9864b1914",
   "metadata": {},
   "source": [
    "### 4.4. Find the Solution's Histogram"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "dfc5f725-495b-45d1-9c67-a1daf80a1454",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.519020Z",
     "iopub.status.busy": "2024-05-07T15:21:50.518676Z",
     "iopub.status.idle": "2024-05-07T15:21:50.523706Z",
     "shell.execute_reply": "2024-05-07T15:21:50.523090Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "energy_vec = []\n",
    "energy_prob = []\n",
    "\n",
    "for value, counts in results.parsed_counts_of_outputs(\"phase\"):\n",
    "    temp = value[1][\"phase\"]\n",
    "    if normalize:\n",
    "        temp2 = (\n",
    "            temp * 2 * normalization_coeff / (1 - (1 / 2**n_qpe))\n",
    "        ) - normalization_coeff\n",
    "    else:\n",
    "        temp2 = temp\n",
    "    energy_vec.append(temp2)\n",
    "    energy_prob.append(counts[1] / num_shots)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "993c5b3b-7a05-44f1-9c4e-6651cd50f4cb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2024-05-07T15:21:50.525902Z",
     "iopub.status.busy": "2024-05-07T15:21:50.525629Z",
     "iopub.status.idle": "2024-05-07T15:21:50.659434Z",
     "shell.execute_reply": "2024-05-07T15:21:50.658856Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAiMAAAGdCAYAAADAAnMpAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuNSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/xnp5ZAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAkF0lEQVR4nO3df3BU1f3/8dcmkIQAWaSBJGAwARRGQaL51eDIjzEaKlUp1kbKSMxY/IWMNNUKtCUfdHQRGWWqjFhbcWqrRDqAo7U4GoyOGgEDVERlhILh1waiZROTmNjs+f7Bl9UAm2SXbM5u8nzM3Bm499yb92Gze1+ce+5dhzHGCAAAwJIo2wUAAIDejTACAACsIowAAACrCCMAAMAqwggAALCKMAIAAKwijAAAAKsIIwAAwKo+tgvoDK/XqyNHjmjgwIFyOBy2ywEAAJ1gjFF9fb2GDRumqCj/4x8REUaOHDmi1NRU22UAAIAgHDx4UOeff77f7RERRgYO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hAs2bN0m233aYdO3ZoxowZmjFjhj755JNurrxzAu2fdPKJlz98nb788sturLjzGhoaNGHCBK1atapT7ffv36/p06dr6tSp2rlzpxYsWKBf/epXeuONN0JcaXAC7d8pe/bsafP6DR06NEQVBu+dd97RvHnz9OGHH+rNN9/Ud999p2uuuUYNDQ1+97H63jMwxhizfPlyk56e7nf7iRMnTN++fc26det86z777DMjyVRWVnZHiUFZs2aNcTqdnWpbVFRkbrjhhpDW09U62z+v12uSk5PNY4895lt34sQJExsba1566aUQVhi4Tz/91Egy27Zt863717/+ZRwOhzl8+LDf/SZPnmzuvffebqgwMDk5OWbevHm+v7e2tpphw4YZl8t11va/+MUvzPTp09usy83NNXfccUdI6wxWoP0L5D0ZTiSZDRs2tNvmt7/9rbnkkkvarCssLDQFBQUhrKxrdKZ/b7/9tpFk/vvf/3ZLTV3p2LFjRpJ55513/Lax+d7rlSMjZ+PxeDR48GC/26uqqvTdd98pPz/ft27s2LEaMWKEKisru6PEblFRUaGhQ4dqzJgxuuuuu/TVV1/ZLqlL7N+/X263u83r53Q6lZubG3avX2VlpQYNGqSsrCzfuvz8fEVFRWnLli3t7vv3v/9diYmJGjdunBYtWqTGxsZQl9uulpYWVVVVtfl3j4qKUn5+vt9/98rKyjbtJamgoCDsXicpuP5J0jfffKMLLrhAqampuuGGG7R79+7uKDfkIum1OxcZGRlKSUnR1Vdfrffff992OZ3i8Xgkqd3znM3XLyK+KC/U9u7dqyeffFIrVqzw28btdismJuaM+QlJSUlheb0wGNOmTdPMmTOVnp6uffv2afHixfrJT36iyspKRUdH2y7vnJx6jZKSktqsD8fXz+12nzHs26dPHw0ePLjdWn/5y1/qggsu0LBhw/Txxx/rgQce0J49e7R+/fpQl+xXbW2tWltbz/rv/vnnn591H7fbHRGvkxRc/8aMGaPnnntOl156qTwej1asWKGJEydq9+7d3fKFoKHk77Wrq6tTU1OT+vXrZ6myrpGSkqLVq1crKytLzc3N+vOf/6wpU6Zoy5Ytuvzyy22X55fX69WCBQt0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Hp6umlqarLRhXZNmzbNXHbZZWbLli3mvffeMxdeeKGZNWuWb/vpv5979+41Dz74oPnoo4/M/v37zSuvvGJGjhxpJk2aZKsLPmvXrjWxsbHm+eefN59++qm5/fbbzaBBg4zb7TbGGHPLLbeYhQsX+tq///77pk+fPmbFihXms88+M6WlpaZv375m165dtrrQrkD7t3TpUvPGG2+Yffv2maqqKnPzzTebuLg4s3v3bltd8Ku+vt733pJkHn/8cbNjxw7z5ZdfGmOMWbhwobnlllt87f/zn/+Y+Ph4c//995vPPvvMrFq1ykRHR5tNmzbZ6kK7Au3fE088YTZu3Gi++OILs2vXLnPvvfeaqKgo89Zbb9nqgl933XWXcTqdpqKios05rrGx0dcmnN57vTKMrFmzxkg663LK/v37jSTz9ttv+9Y1NTWZu+++25x33nkmPj7e/OxnP2sTYMJJUVHRWfv3w/5IMmvWrDHGGNPY2GiuueYaM2TIENO3b19zwQUXmLlz5/o+UMNNoP0z5uTtvX/4wx9MUlKSiY2NNVdddZXZs2dP9xffCV999ZWZNWuWGTBggElISDDFxcVtgtbpv5/V1dVm0qRJZvDgwSY2NtaMHj3a3H///cbj8VjqQVtPPvmkGTFihImJiTE5OTnmww8/9G2bPHmyKSoqatP+5ZdfNhdddJGJiYkxl1xyifnnP//ZzRUHJpD+LViwwNc2KSnJXHvttWb79u0Wqu7YqVtZT19O9aeoqMhMnjz5jH0yMjJMTEyMGTlyZJv3YLgJtH+PPvqoGTVqlImLizODBw82U6ZMMZs3b7ZTfAf8neN++HqE03vP8f+LBgAAsKJH3U0DAAAiD2EEAABYRRgBAABWEUYAAIBVhBEAAGAVYQQAAFhFGAEAAFYRRgAAgFWEEQAAYBVhBAAAWEUYAQAAVhFGAACAVf8PX62Y9BpCK8oAAAAASUVORK5CYII=",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.plot(energy_vec, energy_prob, \".\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9797b512-d41f-47c1-8c0f-4134f0500b80",
   "metadata": {},
   "source": [
    "## References\n",
    "\n",
    "<a name='NC'>[1]</a>: [Michael A. Nielsen and Isaac L. Chuang. 2011. Quantum Computation and Quantum Information: 10th Anniversary Edition, Cambridge University Press, New York, NY, USA.\n",
    "](http://mmrc.amss.cas.cn/tlb/201702/W020170224608149940643.pdf)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
